package com.heima.user.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.redis.CacheService;
import com.heima.model.common.constants.BeHaviorConstants;
import com.heima.model.common.dtos.app.LoginDto;
import com.heima.model.common.dtos.app.UserRelationDto;
import com.heima.model.common.dtos.common.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import com.heima.model.user.pojos.ApUserFan;
import com.heima.model.user.pojos.ApUserFollow;
import com.heima.user.mapper.ApUserFanMapper;
import com.heima.user.mapper.ApUserFollowMapper;
import com.heima.user.service.ApUserFanService;
import com.heima.user.service.ApUserService;
import com.heima.user.mapper.ApUserMapper;
import com.heima.utils.common.AppJwtUtil;
import com.heima.utils.thread.AppThreadLocalUtil;
import com.mysql.jdbc.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
* @author Fu319
* @description 针对表【ap_user(APP用户信息表)】的数据库操作Service实现
* @createDate 2025-03-30 15:54:20
*/
@Service
public class ApUserServiceImpl extends ServiceImpl<ApUserMapper, ApUser> implements ApUserService{
    @Autowired
    private ApUserMapper apUserMapper;
    @Autowired
    private CacheService cacheService;
    @Autowired
    private ApUserFollowMapper apUserFollowMapper;
    @Autowired
    private ApUserFanMapper apUserFanMapper;
    /**
     * APP端登录功能
     * @param loginDto
     * @return
     */
    @Override
    public ResponseResult login(LoginDto loginDto) {
        //判断请求数据是否合法
        if(StringUtils.isNullOrEmpty(loginDto.getPhone())||StringUtils.isNullOrEmpty(loginDto.getPassword())){
            //游客登录
            Map<String, Object> map = new HashMap<>();
            map.put("token",AppJwtUtil.getToken(0L));
            return ResponseResult.okResult(map);
        }
        //正常登录,用户名和密码
        //使用手机号查询用户信息
        LambdaQueryWrapper<ApUser> wrapper=new LambdaQueryWrapper();
        wrapper.eq(ApUser::getPhone,loginDto.getPhone());
        ApUser apUser = apUserMapper.selectOne(wrapper);
        if(apUser==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST);
        }
        //获取该用户的盐
        String salt = apUser.getSalt();
        //将盐和用户登录输入的密码组成新的字符串进行加密
        String loginPassword = DigestUtils.md5DigestAsHex((salt + loginDto.getPassword()).getBytes());
        // 和数据库中的密码进行比对
        if(!apUser.getPassword().equals(loginPassword)){
            return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
        }
        //比对结果为密码匹配则可以响应数据
        //将用户id进行jwt加密,并将用户id,手机号，用户名返回前端
        String token = AppJwtUtil.getToken(apUser.getId());
        apUser =ApUser.builder()
                .id(apUser.getId())
                .phone(apUser.getPhone())
                .name(apUser.getName())
                .build();
        //封装数据
        Map<String, Object> map = new HashMap<>();
        map.put("user",apUser);
        map.put("token",token);
        return ResponseResult.okResult(map);
    }

    /**
     * 关注功能
     * @param dto
     * @return
     */
    @Override
    public ResponseResult follow(UserRelationDto dto) {
        //检验是否登录
        ApUser user = AppThreadLocalUtil.getUser();
        if(user.getId().toString().equals("0")){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        String userId = user.getId().toString();
        ApUser apUser = apUserMapper.selectById(userId);
        //检验参数
        if(dto==null||dto.getArticleId()==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        if(apUser.getId()==dto.getAuthorId()){
            return ResponseResult.errorResult(AppHttpCodeEnum.AUTHOR_NO_FOLLOW_SELF);
        }
        //组装key
        String key= BeHaviorConstants.FOLLOW_AUTHOR+dto.getAuthorId()+":";
        //判断操作类型
        if(dto.getOperation()==0){
            //关注
            if(cacheService.hGet(key,userId)!=null){
                return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR,"您已关注作者，请勿重复操作");
            }
            cacheService.hPut(key,userId, JSON.toJSONString(dto));
            //更新app端用户关注列表(你关注了谁)
            ApUserFollow apUserFollow=ApUserFollow
                    .builder()
                    .createdTime(new Date())
                    .userId(Integer.valueOf(userId))
                    .followId(dto.getAuthorId())
                    .followName(apUser.getName())
                    .level(0) //关注度
                    .isNotice(1) //是否动态通知
                    .build();
            apUserFollowMapper.insert(apUserFollow);
            //更新app端用户粉丝列表(谁关注了你)
            ApUserFan apUserFan=ApUserFan
                    .builder()
                    .createdTime(new Date())
                    .fansId(Integer.valueOf(userId))
                    .userId(dto.getAuthorId())
                    .fansName(apUser.getName())
                    .level(0) //粉丝忠诚度
                    .isDisplay(1) //是否可见我动态
                    .isShieldComment(0)  //是否屏蔽评论
                    .isShieldLetter(0) //是否屏蔽私信
                    .build();
            apUserFanMapper.insert(apUserFan);
        }else{
            //取消关注
            if(cacheService.hGet(key,userId)==null){
                return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR,"您未关注作者，无法取消");
            }
            cacheService.hDelete(key,userId);
            //我删除关注的作者
            LambdaQueryWrapper<ApUserFollow> wrapper=new LambdaQueryWrapper();
            wrapper.eq(ApUserFollow::getFollowId,dto.getAuthorId());
            ApUserFollow apUserFollow = apUserFollowMapper.selectOne(wrapper);
            apUserFollowMapper.deleteById(apUserFollow.getId());
            //作者删除我这个粉丝
            LambdaQueryWrapper<ApUserFan> wrapper2=new LambdaQueryWrapper();
            wrapper2.eq(ApUserFan::getFansId,userId);
            ApUserFan apUserFan2 = apUserFanMapper.selectOne(wrapper2);
            apUserFanMapper.deleteById(apUserFan2.getId());
        }
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}




